package com.jiangkai.common.shiro;

import javax.annotation.Resource;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.jiangkai.common.shiro.rediscache.impl.RedisCacheManager;
import com.jiangkai.entity.system.SysUser;
import com.jiangkai.model.system.ISysUserService;
/**
 * @author jiangkia
 *
 */
public class ShiroDbRealm  extends AuthorizingRealm{
//
	@Autowired 
	private ISysUserService userService; 
    @Resource
    private RedisCacheManager cacheManager;
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principals) {
			System.out.println("doGetAuthorizationInfo:"+principals.toString());
				// TODO Auto-generated method stub
			SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
			//为用户授权,只需将用户的权限添加info中即可
			info.addStringPermission("admin");
			info.addRole("admin");
			return info;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token) throws AuthenticationException {
		SimpleAuthenticationInfo  info = null;
		UsernamePasswordToken upToken = (UsernamePasswordToken) token;
		String username = upToken.getUsername();
		String password = String.valueOf(upToken.getPassword());
		SysUser sysUser = userService.selectOne(new EntityWrapper<SysUser>().eq("userName", upToken.getUsername()));
		if(sysUser == null){
		      throw new UnknownAccountException();  
		}
//		if(!password.equals(user.getPassword())){
//			return null;
//		}
//		String pwd = CryptographyUtil.md5(userInfo.getPassword(), "feicui", 32);
		//TODO 查询数据库用户信息
		Object principal = token.getPrincipal();
		String realmName = this.getName();	
		
		//盐值加密
//		ByteSource credentialsSalt = ByteSource.Util.bytes("feicui");
		//用户注册时用
//		SimpleHash sh = new SimpleHash("MD5", password, null, 1024);
		
		
//		info = new SimpleAuthenticationInfo(principal,sysUser.getPassword(),realmName);
//		return info;
		
		ByteSource byteSource = ByteSource.Util.bytes(sysUser.getUserName());
		info = new SimpleAuthenticationInfo(sysUser,sysUser.getPassword(),byteSource,getName());
		return info;
	}

}
